# -*- coding: utf-8 -*-
"""
@File    : xizang_rikaze_thtml_policy
@Author  : caojy
@Time    : 24/12/03 10:27
"""
import datetime
import json
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class XizangRikaze_thtmlPolicy(BaseTaxPolicySpider):
    name = 'xizang_rikaze_thtml_policy'

    province = '西藏自治区'
    city = '日喀则市'
    county = ''
    park = ''

    def start_requests(self):
        for source, county, url in [
            ['日喀则市聂拉木县人民政府', '聂拉木县', 'http://www.nlmx.gov.cn/public-policy.thtml?id=11681'],
            ['日喀则市聂拉木县人民政府', '聂拉木县', 'http://www.nlmx.gov.cn/public-policy.thtml?id=11682'],
            ['日喀则市拉孜县人民政府', '拉孜县', 'http://www.lazi.gov.cn/public-policy.thtml?id=12918'],
            ['日喀则市拉孜县人民政府', '拉孜县', 'http://www.lazi.gov.cn/public-policy.thtml?id=12919'],
            ['日喀则市昂仁县人民政府', '昂仁县', 'http://www.arx.gov.cn/public-policy.thtml?id=11783'],
            ['日喀则市昂仁县人民政府', '昂仁县', 'http://www.arx.gov.cn/public-policy.thtml?id=11784'],
            ['日喀则市定日县人民政府', '定日县', 'http://www.drx.gov.cn/public-policy.thtml?id=14311'],
            ['日喀则市定日县人民政府', '定日县', 'http://www.drx.gov.cn/public-policy.thtml?id=14312'],
            ['日喀则市南木林县人民政府', '南木林县', 'http://www.nmlx.gov.cn/public-policy.thtml?id=11885'],
            ['日喀则市南木林县人民政府', '南木林县', 'http://www.nmlx.gov.cn/public-policy.thtml?id=11886'],
            ['日喀则市萨迦县人民政府', '萨迦县', 'http://www.sj.gov.cn/public-policy.thtml?id=11991'],
            ['日喀则市萨迦县人民政府', '萨迦县', 'http://www.sj.gov.cn/public-policy.thtml?id=11992'],
            ['日喀则市谢通门县人民政府', '谢通门县', 'http://www.xietongmen.gov.cn/public-policy.thtml?id=12093'],
            ['日喀则市谢通门县人民政府', '谢通门县', 'http://www.xietongmen.gov.cn/public-policy.thtml?id=12094'],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={"item": item})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
                "//div[@class='tab-item show' or @class='new-lists' or @class='list-item']//li//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=2] |"
                "//ul[@class='zfxxgk-nr-cnet']//li//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=2]"
        ):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.thtm' not in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            # pages = response.xpath("//script").re_first(r"""createPageHTML\('page_?-?div',(\d+),""") or response.xpath("//script").re_first(r"""createPageHTML\('paging',(\d+),""") or 0
            count = response.xpath(".").re_first(r"count[:：]?\s*(\d+)")
            if count:
                pages = math.ceil(int(count)/10)
                print(response.url, f"page: {pages}")
                for page_num in range(2, int(pages) + 1):
                    url = response.url + f"&pn={page_num}"
                    yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})
            else:
                next_url = response.xpath("//a[text()='下一页' or text()='下页']/@href").get()
                print("next_url", next_url)
                if next_url != response.url:
                    yield response.follow(next_url, callback=self.parse_list, meta={'item': prev_item})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl xizang_rikaze_thtml_policy".split())
